package com.sys.gradepaysys.config;

import com.sys.gradepaysys.model.Admin;
import com.sys.gradepaysys.model.Student;
import com.sys.gradepaysys.service.AdminService;
import com.sys.gradepaysys.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

@Service
public class MyUserDetailServiceImpl implements UserDetailsService {
    
    @Autowired
    StudentService studentService;
    @Autowired
    AdminService adminService;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        System.out.println(s);

        Student student = studentService.getUserByName(s);
        Admin admin = adminService.getUserByName(s);
        if (student == null && admin == null) {
            throw new BadCredentialsException("用户名不存在，请注册!");
        } else {
            HttpServletRequest request =
                    ((ServletRequestAttributes) RequestContextHolder.
                            getRequestAttributes()).getRequest();
            HttpSession session = request.getSession();
            if (student != null) {
                session.setAttribute("user", student);
            }else {
                session.setAttribute("admin",admin);
            }
        }

        List<SimpleGrantedAuthority> list = new ArrayList<>();
        list.add(new SimpleGrantedAuthority("User"));
        UserDetails userDetails = null;
        if (student != null) {
            userDetails = new User(student.getgName(),
                    student.getPassword(), list);
        }else {
            userDetails = new User(admin.getUsername(),
                    admin.getPassword(), list);        
        }
        return userDetails;
    }
}
